package com.qingmeng.project.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingmeng.apicommon.model.entity.InterfaceInfo;
import com.qingmeng.project.mapper.UserInterfaceInfoMapper;
import com.qingmeng.project.model.entity.InterfaceInfoCount;
import com.qingmeng.project.model.vo.InterfaceInfoVo;
import com.qingmeng.project.service.CountInterfaceService;
import com.qingmeng.project.service.InterfaceInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CountInterfaceInfoServiceImpl implements CountInterfaceService {
    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoService InterfaceInfoService;

    /**
     * 接口调用统计
     * @return
     */
    @Override
    public List<InterfaceInfoVo> countInterface() {
        //查询接口调用次数详情
        List<InterfaceInfoCount> UserInterfaceList = userInterfaceInfoMapper.countInterface(5);
        // 输出
        System.out.println(JSONUtil.toJsonStr(UserInterfaceList));
           List<InterfaceInfoCount> NewUserInterfaceList = UserInterfaceList.stream()
           .filter(item -> item.getInterfaceId() != null)
           .collect(Collectors.toList());
           System.out.println(JSONUtil.toJsonStr(NewUserInterfaceList));
        //将接口信息按照接口id分组，便于关联查询
        Map<Long,List<InterfaceInfoCount>> interfaceInfoMap = NewUserInterfaceList.stream()
                .collect(Collectors.groupingBy(InterfaceInfoCount::getInterfaceId));
        System.out.println(JSONUtil.toJsonStr(interfaceInfoMap));
        //构建一个查询接口详细信息的条件包装器
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",interfaceInfoMap.keySet());
        //查询接口详细信息
        List<InterfaceInfo> interfaceInfos1 = InterfaceInfoService.list(queryWrapper);

        //将接口调用次数和接口详细信息封装到InterfaceInfoVo对象中并返回
        List<InterfaceInfoVo> interfaceInfoVoList = interfaceInfos1.stream() .map(interfaceInfo -> {
            //创建一个新的InterfaceInfoVO对象
            InterfaceInfoVo interfaceInfoVo = new InterfaceInfoVo();
            //将接口详细信息复制到VO对象中
            BeanUtils.copyProperties(interfaceInfo,interfaceInfoVo);
            //从接口信息id对应的映射中获取接口调用次数
            Integer countNum = interfaceInfoMap.get(interfaceInfo.getId()).get(0).getCountNum();
            //设置接口调用次数
            interfaceInfoVo.setCountSum(countNum);
            return interfaceInfoVo;
        }).collect(Collectors.toList());
        return interfaceInfoVoList;
    }
}
